package com.taxigang.server;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import com.taxigang.shared.TaxiCompanyInfo;
import com.taxigang.shared.TaxiGangInfo;

public class TaxiCompanyDAO {
	private EntityManager em;
	public TaxiCompanyDAO(EntityManager em){
		this.em = em;
	}
	private static long DISTANCE = 3;

	public TaxiCompanyInfo[] find(TaxiGangInfo taxiganginfo) {

		Query query = em.createNamedQuery("TaxiCompany.findAll");

		List<TaxiCompanyInfo>taxiCompanyInfoList = new ArrayList<TaxiCompanyInfo>();
		Collection<TaxiCompany> taxiCompanyList = query.getResultList();
		int size = taxiCompanyList.size();

		long startGeobox = GeoBox.getInstance().getIndex(taxiganginfo.getStartLat(),taxiganginfo.getStartLng());
		long destGeobox = GeoBox.getInstance().getIndex(taxiganginfo.getDestinationLat(),taxiganginfo.getDestinationLng());
		for (TaxiCompany taxiCompany : taxiCompanyList){
			TaxiCompanyInfo taxiCompanyInfo = taxiCompany.getInfo();
			if (!taxiCompanyInfoList.contains(taxiCompanyInfo)){
				if (GeoBox.getInstance().isNearby(DISTANCE,startGeobox, destGeobox,taxiCompanyInfo.getLat(), taxiCompanyInfo.getLng())){
					taxiCompanyInfoList.add(taxiCompanyInfo);
				}
			}
		}

		return taxiCompanyInfoList.toArray(new TaxiCompanyInfo[0]);
	}

	public void create(TaxiCompanyInfo taxiCompanyInfo) {
		EntityTransaction transaction = em.getTransaction();
		try{
			transaction.begin();
			TaxiCompany taxiCompany = new TaxiCompany();
			taxiCompany.setInfo(taxiCompanyInfo);
			em.persist(taxiCompany);
		} catch(Exception ex){
			ex.printStackTrace();
		} finally {
			transaction.commit();
		}
	}



}
